package icu.lookyousmileface.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author starrysky
 * @title: ShiroConfig
 * @projectName spring-shiro-parent
 * @description: config layer
 * @date 2021/2/1021:15
 */
@Configuration
public class ShiroConfig {

    /**
     * 关联defaultWebSecretary
     *
     * @param defaultWebSecurityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//        设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

//        添加shiro的内置过滤器
        /*
            anon：无须登陆就可以访问
            authc： 必须认证了才能访问
            user：必须拥有 记住我 功能才能用
            perms：拥有对某个资源的权限才能访问
            role：拥有某个角色权限才能访问
         */

        Map<String,String> filterMap = new LinkedHashMap<>(16, 0.75F);

//        perms[user:add]用户拥有的权限
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");
//        设置拦截规则
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
//        设置登陆页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
//        未经授权的页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/authorizedPage");
        return shiroFilterFactoryBean;
    }

    /**
     * 关联realm容器
     *
     * @return
     */
    @Bean("defaultWebSecurityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        defaultSecurityManager.setRealm(userRealm);
        return defaultSecurityManager;
    }

    /**
     * 生成realm的容器
     *
     * @return
     */
    @Bean("userRealm")
    public UserRealm userRealm() {
        return new UserRealm();
    }

    /**
     * 用于shiro和thymeleaf的整合
     * @return
     */
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
